#!/usr/bin/perl -w

#####################################################################
# Program Variables - Go see the central config.pm!
#####################################################################
use FindBin qw($Bin);
use lib "$Bin/..";
use config;
use layout;

#####################################################################
# Program Modules
#####################################################################
# CGI Modules
use CGI;
use CGI::Carp;
use CGI::Pretty;

# Database Modules
use DBI;

# Data::Dumper for debugging
#use Data::Dumper;

# POSIX Stuff...
use POSIX;

#####################################################################
# Program Start
#####################################################################
my $cgi = new CGI;

my $pagetitle = &read_config_option("tank_name") . " Water Statistics Configuration";

# Web Page output
&ts_pagestart($pagetitle);

# Parameter List Checking
my %params = $cgi->Vars;

foreach $key (keys %params) {
    print $cgi->comment("$key") . "\n";

    if ($key eq "add_test") {
        &edit_test(undef);
    } elsif ($key eq "write_test") {
        &write_test(%params);
    } elsif ($key =~ /edit_(.*)/i) {
        &edit_test($1);
    } elsif ($key =~ /delete_(.*)/i) {
        &delete_test($1);
    }
}

#######################################
# Get the most recent statistics

my @tablerows;
push(
    @tablerows,
    $cgi->th([
            "Short Name",
            "Display Order",
            "Multiplier",
            "Multiplier Title",
            "Graph Title",
            "Graph Minimum",
            "Graph Maximum",
            "Graph Line Colour",
            "Graph Average Colour",
            "&nbsp;"
        ]));

my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

# Collate the most recent data.
my $test_sth = $dbh->prepare("SELECT ROWID,* FROM tests ORDER BY displayorder ASC");
$test_sth->execute();
while (my $testref = $test_sth->fetchrow_hashref()) {
    my %testhash = %{$testref};

    push(
        @tablerows,
        $cgi->td([
                $testhash{name}			|| "&nbsp;",
                $testhash{displayorder}		|| "&nbsp;",
                $testhash{multiplier}		|| "&nbsp;",
                $testhash{multipliertitle}	|| "&nbsp;",
                $testhash{title}		|| "&nbsp;",
                $testhash{graphmin}		|| "&nbsp;",
                $testhash{graphmax}		|| "&nbsp;",
                $testhash{graphlinecolour}	|| "&nbsp;",
                $testhash{graphavgcolour}	|| "&nbsp;",
                $cgi->submit(-name => "edit_$testhash{rowid}", -label => "Edit") . " | "
                  . $cgi->submit(-name => "delete_$testhash{rowid}", -label => "Delete") ]));
}

push(@tablerows, $cgi->td({ colspan => "11" }, $cgi->submit(-name => "add_test", -label => "Add Water Test")));

# Close the database
$test_sth->finish;
$dbh->disconnect;
#######################################

# Start the forms
print $cgi->start_form;
print $cgi->start_table({ -align => 'center' });
print $cgi->Tr([@tablerows]);
print $cgi->end_table;
print $cgi->end_form;
print $cgi->p($cgi->center("Return to the " . $cgi->a({ -href => "./" }, &read_config_option("tank_name") . " Configuration Index") . " Page."));
print $cgi->end_html;
print "\n";
exit 0;

#####################################################################
# Program Subroutines
#####################################################################
sub edit_test {
    my $testid = shift @_;
    my %testhash;

    if (defined($testid)) {
        my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
        my $testref = $dbh->selectrow_hashref("SELECT * FROM tests WHERE ROWID=?", undef, $testid);
        if (defined($testref)) {
            %testhash = %{$testref};
        }
    }

    # Start the forms
    print $cgi->start_form;
    if (defined($testid)) {
        print $cgi->hidden(-name => "testid", -value => $testid);
    }

    print $cgi->start_table({ -align => 'center' });
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Short Name"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "name", -default => $testhash{name} || "", -size => "20") ]) ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Display Order"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "displayorder", -default => $testhash{displayorder} || "", -size => "5") ])
        ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Multiplier"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "multiplier", -default => $testhash{multiplier} || "", -size => "10") ]) ]);
    print $cgi->Tr([
            $cgi->th({ -class => "right" }, ["Multiplier Title"])
              . $cgi->td(
                { -class => "left" },
                [ $cgi->textfield(-name => "multipliertitle", -default => $testhash{multipliertitle} || "", -size => "50") ]) ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Graph Title"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "title", -default => $testhash{title} || "", -size => "50") ]) ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Graph Minimum"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "graphmin", -default => $testhash{graphmin} || "", -size => "10") ]) ]);
    print $cgi->Tr([
                $cgi->th({ -class => "right" }, ["Graph Maximum"])
              . $cgi->td({ -class => "left" }, [ $cgi->textfield(-name => "graphmax", -default => $testhash{graphmax} || "", -size => "10") ]) ]);
    print $cgi->Tr([
            $cgi->th({ -class => "right" }, ["Graph Line Colour"])
              . $cgi->td(
                { -class => "left" },
                [ $cgi->textfield(-name => "graphlinecolour", -default => $testhash{graphlinecolour} || "", -size => "20") ]) ]);
    print $cgi->Tr([
            $cgi->th({ -class => "right" }, ["Graph Average Colour"])
              . $cgi->td(
                { -class => "left" },
                [ $cgi->textfield(-name => "graphavgcolour", -default => $testhash{graphavgcolour} || "", -size => "20") ]) ]);
    print $cgi->Tr([
            $cgi->td(
                { -colspan => "2" },
                [ $cgi->submit(-name => "write_test", -label => "Save") . " | " . $cgi->reset . " | " . $cgi->a({ -href => "stats.cgi" }, "Back") ]) ]
    );
    print $cgi->end_table;
    print $cgi->end_form;
    print $cgi->end_html;
    print "\n";
    exit 0;

}

# Write/Upoate the test to the database
sub write_test {
    my %testhash = @_;
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");
    if (defined($testhash{testid})) {

        # If given the row id, then we are updating the database
        $dbh->do(
"UPDATE tests SET name=?, displayorder=?, multiplier=?, multipliertitle=?, title=?, graphmin=?, graphmax=?, graphlinecolour=?, graphavgcolour=? WHERE ROWID=?",
            undef,
            $testhash{name},
            $testhash{displayorder},
            $testhash{multiplier},
            $testhash{multipliertitle},
            $testhash{title},
            $testhash{graphmin},
            $testhash{graphmax},
            $testhash{graphlinecolour},
            $testhash{graphavgcolour},
            $testhash{testid});
    } else {

        # Otherwise we are adding a new record
        $dbh->do(
"INSERT INTO tests (name, displayorder, multiplier, multipliertitle, title, graphmin, graphmax, graphlinecolour, graphavgcolour) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            undef,
            $testhash{name},
            $testhash{displayorder},
            $testhash{multiplier},
            $testhash{multipliertitle},
            $testhash{title},
            $testhash{graphmin},
            $testhash{graphmax},
            $testhash{graphlinecolour},
            $testhash{graphavgcolour});
    }

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Entry Added/Updated"), "\n";
    $cgi->delete_all();
    return;
}

# Delete the selected test from the database
sub delete_test {
    my $entry = shift @_;

    # Open the database
    my $dbh = DBI->connect("dbi:SQLite:dbname=$database_file", "", "");

    # Delete the record
    $dbh->do("DELETE FROM tests WHERE ROWID=?", undef, $entry);

    # Close the database
    $dbh->disconnect;

    print $cgi->comment("Entry $entry Deleted"), "\n";
    $cgi->delete_all();
    return;
}

